<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/21
 * Time: 9:42
 */

namespace app\service;


use app\alliance\controller\Mine;
use Redis\Redis;
use think\App;
use think\Controller;
use think\Db;

class TaskService extends Controller
{
    private $MemberCode;
    private $MemberLevel;
    function __construct($member_code, $member_level,App $app = null)
    {
        parent::__construct($app);
        $this->MemberCode = $member_code;
        $this->MemberLevel = $member_level;
    }

    public function taskInit()
    {
        # 初始化任务
        $_redis = new Redis();
        $_init = $_redis->hGet('task', "init_" . $this->MemberCode);
        if (empty($_init)) {
            $_time = strtotime(date("Y-m-d 23:59:59")) - time();
            $_redis->hSet('task', "init", "1", $_time);
            $this->taskAdd();
        }
    }

    /**
     * @param int $num
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 用户任务添加
     */
    function taskAdd($num = 3)
    {
        # 查询当前用户有多少未完成的任务
        $_now_task = Db::table("member_task mt")->field('task_id')->leftJoin('task t', 't.id=mt.task_id')
            ->where("finish_status!=3 and member_code='{$this->MemberCode}' and main_task=2")->select();
//        $_limit = $num - $_now_task;
//        if ($_limit > 0) {
        if (!empty($_now_task)) {
            $_idWhere = " id not in (" . implode(',', array_column($_now_task, 'task_id')) . ")";
        } else {
            $_idWhere = '';
        }
        # 添加任务
        $list = Db::table("task")
            ->field("id,task_title,task_type,task_number,task_desc")
            ->where("level_limit ={$this->MemberLevel} and task_status=1 and main_task=2 
         and 
         (
            (circulation=2 and id not in (select task_id from member_task where member_code = '{$this->MemberCode}')) 
            or
            (circulation=1 and (DATE_SUB(NOW(),INTERVAL circulation_period day)<=(select finish_time from member_task where task_id=task.id and finish_status=3 order by id desc limit 1)
                                    or
                                    (id not in (select task_id from member_task where member_code = '{$this->MemberCode}'))
                                )
          )
          )
          ")->where($_idWhere)->select();//->limit($_limit)
        # 判断是否存在未完成的主任务
        $mainTask = Db::table('member_task mt')
            ->leftJoin('task t', 't.id=mt.task_id')
            ->where("mt.finish_status != 3")
            ->where(array('member_code' => $this->MemberCode, 'main_task' => 1))
            ->find();
        if (empty($mainTask)) {
            # 查询添加主任务
            $taskInfo = Db::table('task')->field('id,task_title,task_type,task_number,task_desc')->where(array('main_task' => 1))->find();
            array_push($list, $taskInfo);
        }
        if (empty($list)) {
            return array("status" => false);
        } else {
            $_array = array();
            foreach ($list as $k => $v) {
                array_push($_array, array("member_code" => $this->MemberCode, "task_id" => $v['id'], "task_plan" => 0, "finish_status" => 1));
            }
            Db::table("member_task")->insertAll($_array);
            return array("status" => true, "data" => $list);
        }
//        } else {
//            return array("status" => false);
//        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 获取用户任务列表
     */
    function taskList()
    {
        $list = Db::table("member_task mt")
            ->field("mt.id,mt.member_code,mt.task_id,mt.task_plan,mt.finish_status,t.task_title,t.task_type,t.task_number,t.task_desc")
            ->join("task t", "t.id = mt.task_id")
            ->where("mt.finish_status<3 and mt.member_code='{$this->MemberCode}'")
            ->order("t.main_task asc,mt.finish_status desc")
            ->select();
        if (!empty($list)) {
            return array("status" => true, "data" => $list);
        } else {
            return array("status" => false);
        }
    }

    /**
     * @return float|string
     * @context 用户有多少未完成的任务
     */
    function taskCount()
    {
        $list = Db::table("member_task mt")
            ->where("mt.finish_status<3 and mt.member_code='{$this->MemberCode}'")
            ->count();
        return $list;
    }

    /**
     * @param string $memberCode 玩家ID
     * @param int $taskType 任务类型==>
     * 1 推荐玩家
     * 2 达成级别
     * 3 转轮摇奖
     * 4 金币转账
     * 5 团队人数
     * 6 发红包
     * 7 连续签到
     * 8 生意出售
     * 9 生意购买
     * 10 兑换材料
     * 11 积分转账
     * 12 生意交租
     * 13 激活账号
     * 14 首次注册
     * 15 打劫玩家
     * 16 反击玩家
     * 17 每日答题
     * 18 卡券使用
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 完成任务
     */
    function finishTask($memberCode, $taskType)
    {
        if (!empty($memberCode) and !empty($taskType)) {
            # 查询是否存在未完成的该类型的任务
            $taskInfo = Db::table('member_task mt')
                ->field('mt.id,mt.task_plan,t.task_number')
                ->leftJoin('task t', 't.id=mt.task_id')
                ->where(array('t.task_type' => $taskType, 'mt.finish_status' => 1, 'mt.member_code' => $memberCode))
                ->select();
            if (!empty($taskInfo)) {
                $redis = new Redis();
                $getui = new IGeTuiService();
                $getuiState = false;
                foreach ($taskInfo as $k => $v) {
                    $completeNum = $v['task_plan'] + 1;
                    if ($completeNum == 1) {
                        if ($taskType == 2) {
                            # 达成级别,
                            $completeNum = $redis->hGetJson('memberInfo', $memberCode)['level'];
                        } elseif ($taskType == 5) {
                            # 团队人数
                            $completeNum =Db::table('member')->field('code')
                                ->where("code != '" . $memberCode . "'")
                                ->where("level >= 3")
                                ->where("(code in ((select code from member where p_code in 
            (select code from member where p_code in(select code from member where p_code = '".$memberCode."'))),
            (select code from member where p_code in(select code from member where p_code = '".$memberCode."')),
            (select code from member where p_code = '".$memberCode."')))")->count();
                            if (empty($completeNum)) {
                                $completeNum = 0;
                            }
                        } elseif ($taskType == 7) {
                            # 连续签到
                            $completeNum = $redis->hGet('memberSignNum', $memberCode);
                            if (empty($completeNum)) {
                                $completeNum = 0;
                            }
                        }
                    }
                    if ($completeNum >= $v['task_number']) {
                        # 已完成,修改状态
                        $getuiState = true;
                        $_arr = array('task_plan' => $completeNum, 'finish_status' => 2, 'finish_time' => date("Y-m-d H:i:s"));
                    } else {
                        $_arr = array('task_plan' => $completeNum);
                    }
                    Db::table('member_task')->where(array('id' => $v['id']))->update($_arr);
                }
                if ($getuiState) {
                    # 发送领取任务奖励通知
                    $getui->pushMessageToSingle('完成任务', '任务提醒', '有可领取的任务奖励,立即领取', $memberCode);
                }
                $upgrade = TaskService::gradeIntroduce($memberCode);
                if ($upgrade['canUpgrade'] == 'YES') {
                    $getui->pushMessageToSingle('升级提醒', '升级提醒', '升级任务全部完成,立即去升级', $memberCode);
                }
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '用户任务不存在');
            }
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    function gradeIntroduce($memberCode)
    {
        $redis = new Redis();
        $memberInfo = $redis->hGetJson('memberInfo', $memberCode);
        if (empty($memberInfo)) {
            $memberInfo = MemberService::checkMemberRegister($memberCode, 'account')['info'];
        }
        if (!empty($memberInfo)) {
            # 查询用户当前等级信息
            $currentLevelInfo = $redis->hGetJson('memberLevelInfo', strval($memberInfo['level']));
            if (empty($currentLevelInfo)) {
                $currentLevelInfo = Db::table('member_level')->where(array('level' => $memberInfo['level']))->find();
                $deduct = jobService::getLevelDeduct($memberInfo['level']);
                $currentLevelInfo['direct'] = $deduct[0];
                $currentLevelInfo['indirect'] = $deduct[1];
                $redis->hSetJson('memberLevelInfo', strval($memberInfo['level']), $currentLevelInfo);

            }
            # 查询用户下一个等级信息
            $nextLevel = $memberInfo['level'] + 1;
            if ($nextLevel > 12) {
                $nextLevelInfo = array();
                $nextLevelMsg = "已经是最高等级";
            } else {
                $nextLevelInfo = $redis->hGetJson('memberLevelInfo', strval($nextLevel));
                if (empty($nextLevelInfo)) {
                    $nextLevelInfo = Db::table('member_level')->where(array('level' => $nextLevel))->find();
                    $deduct = jobService::getLevelDeduct($nextLevel);
                    $nextLevelInfo['direct'] = $deduct[0];
                    $nextLevelInfo['indirect'] = $deduct[1];
                    $redis->hSetJson('memberLevelInfo', strval($nextLevel), $nextLevelInfo);
                }
                $nextLevelMsg = $nextLevelInfo['title'];
            }
            # 是否可以升级
            $canUpgrade = 'YES';
            # 升级标准(需要有多少个等级玩家)
            $gradeNumberLimit = array();
            if ($nextLevelInfo['is_limits'] == 2) {
                $gradeNumberLimit = Db::table('industry_level_limits ill')
                    ->field('member_num,member_level,title,
                if(member_num <= (select count(id) from member where level=ill.member_level and team_id = ' . $memberInfo['team_id'] . '),0,1) isCompleted')
                    ->leftJoin('member_level ml', 'ml.level=ill.member_level')
                    ->where(array('ill.level_id' => $nextLevelInfo['id']))
                    ->order("member_level asc")
                    ->select();
                if (!empty($gradeNumberLimit)) {
                    if (in_array(0, array_column($gradeNumberLimit, 'isCompleted'))) {
                        $canUpgrade = 'NO';
                    }
                }
            }
            # 判断升级条件是否满足(默认满足)(交易次数 , 直推人数 , 团队人数 , 消费金额限制)
            $upgradeStandard = array('trade_num_complete' => 1, 'share_num_complete' => 1, 'team_people_complete' => 1, 'consumption_amount_complete' => 1);
            if ($nextLevelInfo['trade_num'] > 0) {
                # 查询交易次数
                $tradNum = Db::table('log_trad')->where("seller_code = '" . $memberCode . "' or buyer_code = '" . $memberCode . "'")->count();
                if ($tradNum < $nextLevelInfo['trade_num']) {
                    $upgradeStandard['trade_num_complete'] = 0;
                    $canUpgrade = 'NO';
                }
            }
            if ($nextLevelInfo['share_num'] > 0) {
                # 查询直推人数
                $shareNum = Db::table('member')->where(array('p_code' => $memberCode))->count();
                if ($shareNum < $nextLevelInfo['share_num']) {
                    $upgradeStandard['share_num_complete'] = 0;
                    $canUpgrade = 'NO';
                }
            }
            if ($nextLevelInfo['team_people'] > 0) {
                # 查询团队人数
                $teamNum = Db::table('team')->field('team_num')->where(array('id' => $memberInfo['team_id']))->find()['team_num'];
                if ($teamNum < $nextLevelInfo['team_people']) {
                    $upgradeStandard['team_people_complete'] = 0;
                    $canUpgrade = 'NO';
                }
            }
            if ($nextLevelInfo['consumption_amount'] > 0) {
                # 消费金额限制
                $consumptionAmount = Db::table('log_integral')->where(array('member_code' => $memberCode, 'type_branch' => 7))->sum('total_money');
                if ($consumptionAmount < $nextLevelInfo['consumption_amount']) {
                    $upgradeStandard['consumption_amount_complete'] = 0;
                    $canUpgrade = 'NO';
                }
                $upgradeStandard['diff'] = $nextLevelInfo['consumption_amount'] - $consumptionAmount;

            }
            $redis->hSet('MemberCanUpgrade', $memberCode, $canUpgrade);
            if ($canUpgrade == 'YES') {
                # 获取当前用户可开启的栏位
                $res = Db::table("member_business_grid")->where(array("member_code" => $memberCode, "grid" => $nextLevel + 1, "status" => 0))->update(array("status" => 2));
                if ($res) {
                    # 修改栏位缓存
                    $list = $redis->hGetJson("member_business", $memberCode);
                    if (!empty($list)) {
                        $list[$nextLevel]['open_status'] = 2;
                        $redis->hSetJson("member_business", $memberCode, $list);
                    }
                }
            }
            return array('status' => true, 'msg' => '查询成功', 'currentLevelInfo' => $currentLevelInfo,
                'nextLevelInfo' => $nextLevelInfo, 'nextLevelMsg' => $nextLevelMsg, 'gradeNumberLimit' => $gradeNumberLimit,
                'upgradeStandard' => $upgradeStandard, 'canUpgrade' => $canUpgrade);
        }
    }

}